<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
  <div class="min-h-screen max-w-[1440px] mx-auto bg-white">
    <!-- 轮播图区域 -->
    <div class="relative h-[400px] overflow-hidden">
      <swiper
          :modules="swiperModules"
          :slides-per-view="1"
          :loop="true"
          :autoplay="{ delay: 3000 }"
          :pagination="{ clickable: true }"
          class="h-full"
      >
        <swiper-slide v-for="(pic, index) in scenicSpot.picList" :key="index">
          <div class="relative w-full h-full">
            <img :src="SERVER_ADDR + '/scenicSpot/pic/' + pic.url" class="w-full h-full object-cover" alt="景区图片" />
          </div>
        </swiper-slide>
      </swiper>
    </div>

    <!-- 景区信息 -->
    <div class="px-8 py-6 bg-white">
      <h1 class="text-3xl font-bold mb-4">{{ scenicSpot.name}}</h1>
      <p class="text-gray-600 leading-7">
        {{scenicSpot.description}}
      </p>
    </div>

    <!-- 选票区域 -->
    <div class="px-8 py-6">
      <div class="bg-white rounded-lg shadow-md p-6">
        <!-- 日期选择 -->
        <div class="mb-6">
          <h2 class="text-xl font-bold mb-4">选择参观日期</h2>
          <el-date-picker
              v-model="selectedDate"
              type="date"
              :disabled-date="disabledDate"
              placeholder="请选择日期"
              format="YYYY-MM-DD"
              class="w-full"
          />
        </div>

        <!-- 票型选择 -->
        <div class="space-y-4">
          <h2 class="text-xl font-bold mb-4">选择门票</h2>

          <div v-for="ticket in tickets" :key="ticket.type"
               class="flex items-center justify-between p-4 border rounded-lg hover:border-blue-500 transition-colors">
            <div class="flex-1">
              <h3 class="text-lg font-medium">{{ ticket.name }}</h3>
              <p class="text-gray-500 text-sm mt-1">{{ ticket.description }}</p>
              <p class="text-red-500 font-medium mt-2">¥ {{ Number(ticket.price).toFixed(2) }}</p>
            </div>
            <div class="flex items-center space-x-3">
              <el-button
                  :disabled="ticket.count <= 0"
                  @click="updateTicketCount(ticket, -1)"
                  class="!rounded-button"
              >
                <el-icon><Minus /></el-icon>
              </el-button>
              <span class="w-8 text-center">{{ ticket.count }}</span>
              <el-button
                  @click="updateTicketCount(ticket, 1)"
                  class="!rounded-button"
              >
                <el-icon><Plus /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 景区须知 -->
      <div class="mt-6 bg-white rounded-lg shadow-md p-6">
        <h2 class="text-xl font-bold mb-4">景区须知</h2>
        <div class="space-y-3">
          <div v-for="(notice, index) in notices" :key="index" class="flex items-start space-x-2">
            <el-icon class="text-blue-500 mt-1"><InfoFilled /></el-icon>
            <p class="text-gray-600">{{ notice }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部结算栏 -->
    <div class="fixed bottom-0 left-0 right-0 bg-white border-t shadow-lg">
      <div class="max-w-[1440px] mx-auto px-8 py-4 flex items-center justify-between">
        <div>
          <p class="text-gray-600">总计</p>
          <p class="text-2xl font-bold text-red-500">¥ {{ totalPrice }}</p>
        </div>
        <el-button
            type="primary"
            :disabled="!canBook"
            class="!rounded-button whitespace-nowrap px-12"
            @click="handleBooking"
        >
          立即预订
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { Swiper, SwiperSlide } from 'swiper/vue';
import { Pagination, Autoplay } from 'swiper/modules';
import { ElMessage } from 'element-plus';
import { Minus, Plus, InfoFilled } from '@element-plus/icons-vue';
import {useRoute, useRouter} from "vue-router";
import {useTokenStore} from "@/stores/tokenStore.js";
import scenicSpotApi from "@/api/scenicSpotApi"
import orderApi from "@/api/orderApi.js";

const router = useRouter();
const route  = useRoute();
const tokenStore = useTokenStore();
//服务器的地址
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR)
const swiperModules = [Pagination, Autoplay];

const bannerImages = [
  'https://ai-public.mastergo.com/ai/img_res/b9ba897f82f2a1c8c53da45a304d2b04.jpg',
  'https://ai-public.mastergo.com/ai/img_res/21ed7bf2ef2a5aa87ac5ce93f39fc2f6.jpg',
  'https://ai-public.mastergo.com/ai/img_res/6fc73de9018b66528840358636e4839a.jpg'
];

const selectedDate = ref('');

const tickets = ref([
  {
    type: 1,
    name: '成人票',
    description: '适用于18-60周岁游客',
    price: '',
    count: 0
  },
  {
    type: 2,
    name: '儿童票',
    description: '适用于1.2-1.5米儿童',
    price: '',
    count: 0
  },
  {
    type: 3,
    name: '学生票',
    description: '需要提供有效学生证',
    price: '',
    count: 0
  }
]);

const notices = [
  '门票当天有效，请在预订日期使用',
  '学生票需要在入园时出示有效学生证',
  '儿童票需要测量身高，不符合要求需补差价',
  '景区开放时间：旺季 6:30-17:30，淡季 7:00-17:00',
  '门票包含景区内观光车服务'
];
// 定义景点
const scenicSpot = ref({
  id: null,
  name: null,
  description: null,
  addr: {
    province: null,
    city: null,
    district: null,
    street: null,
    address: null,
    postCode: null,
  },
  ticketPrice: null,
  openTime: null,
  recommendDuration: null,
  suitableFor: null,
  isRecommended: null,
  tags: null,
  status: null,
  picList: [],
  detail: null,
  route: null,
  categoryId: null,
  contactTel: null,
});
// 获取景点信息
const selectById = ()=>{
  let id = route.query.id;
  scenicSpotApi.selectById(id)
      .then(resp => {
        scenicSpot.value = resp.data
        scenicSpot.value.tags = scenicSpot.value.tags.split(",");
        scenicSpot.value.suitableFor = scenicSpot.value.suitableFor.split(",");
        tickets.value[0].price = resp.data.ticketPrice;
        tickets.value[1].price = resp.data.ticketPrice * 0.8;
        tickets.value[2].price = resp.data.ticketPrice * 0.5;
      })
}
// 统计总价格
const totalPrice = computed(() => {
  return tickets.value.reduce((sum, ticket) => {
    return sum + ticket.price * ticket.count;
  }, 0);
});

const canBook = computed(() => {
  return selectedDate.value && tickets.value.some(ticket => ticket.count > 0);
});

const updateTicketCount = (ticket, delta) => {
  const newCount = ticket.count + delta;
  if (newCount >= 0) {
    ticket.count = newCount;
  }
};

const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7;
};

// const handleBooking = () => {
//   ElMessage.success('预订成功！');
// };
// 生成订单跳转到支付界面
const handleBooking = () => {
  console.log(tickets.value)
  if (!selectedDate.value) {
    ElMessage.error('请选择日期');
    return;
  }

  if (!canBook.value) {
    ElMessage.error('请选择至少一张票');
    return;
  }
  const orderVo = {
    scenicSpotId: route.query.id,
    preOrderDate: selectedDate.value,
    tickets: tickets.value.map(ticket => ({
      ticketType: ticket.type,
      count: ticket.count,
      price: ticket.price,
      payPwd: ''
    })),
  };
  // 加载中
  ElMessage('订单生成中请稍等')
  orderApi.insert(orderVo).then(resp => {
    if (resp.code == 10000) {
      ElMessage.success(resp.msg);
      // 生成订单跳转到支付界面
      router.push({
        path: '/user/pay',
        query: {
          orderId: resp.data.orderId
        }
      })
    } else {
      ElMessage.error(resp.msg)
    }
  })
}
selectById();
</script>

<style scoped>
.el-date-picker {
  --el-datepicker-border-color: #e5e7eb;
}

:deep(.swiper-pagination-bullet) {
  background: white;
  opacity: 0.8;
}

:deep(.swiper-pagination-bullet-active) {
  background: white;
  opacity: 1;
}
</style>
